<template>
  <su-page>
    <su-body padding="0 15px">
      <u--form labelPosition="top" :model="formData" :rules="rules" ref="form1">
        <u-form-item labelWidth="100px" label="标题" prop="bt" borderBottom ref="item1">
          <u--input v-model="formData.bt" placeholder="请输入标题" border="none"></u--input>
        </u-form-item>
        
        <u-form-item labelWidth="100px" label="内容" prop="nr" borderBottom ref="item1">
          <u--textarea v-model="formData.nr" placeholder="请输入内容"  border="none"></u--textarea>
        </u-form-item>
				<u-form-item labelWidth="100px" label="发送单位" prop="jsdw" borderBottom ref="item1">
					 <u--input v-model="formData.fsdw" placeholder="发送单位" border="none" readonly></u--input>
				</u-form-item>
        <u-form-item labelWidth="100px" label="附件" prop="files" borderBottom ref="item1">
					<view class="su-uploader">
						<view class="su-uploader-handler" @click="chooseWxFile">
						  +
						</view>
						<view class="su-uploader-images-item" v-for="(item,index) in formData.files" :key="index">
						  <view class="su-uploader-images-delete" @click="deleteItem(item,index)">
						    <u-icon name="close" color="#ff0000" size="18"></u-icon>
						  </view>
						  <u--image radius="6" :src="item.imgurl" width="70" height="70" mode="aspectFill" @click="previewImg(index)"></u--image>
						</view>
					</view>
        </u-form-item>
      </u--form>
      <su-fixed-footer transparent>
        <u-button type="primary" size="large" :loading="loading" text="提交" @click="submitForm"></u-button>
      </su-fixed-footer>
    </su-body>
		<u-toast ref="uToast"></u-toast>
  </su-page>
</template>

<script>
  /* @Description: 通知发送
  * @Author: Yinchy
  * @CreatDate: 2022-11-22 17:01:55
  * @Params: 
  */
import { runSQL, uploadFilePath,fileIcon } from '../../../../common/utils/wxutils'
  export default {
    data() {
      return {
        loading: false,
        formData: {
          bt: '',
          fsdw: '',
          nr: '',
          fsr: JSON.parse(uni.getStorageSync('userInfo')).HUMANNAME || '',
          fsrid: JSON.parse(uni.getStorageSync('userInfo')).HUMANID || 100,
          fsdw: JSON.parse(uni.getStorageSync('userInfo')).UNITNAME || '',
          fsdwid: parseInt(JSON.parse(uni.getStorageSync('userInfo')).UNITID) || 1946,
          files: [],//存放小程序选择完的路径
        },
				serverFiles: [],//存放上传后的服务器返回的file信息
				fileStr: '',
        // 表单校验规则
        rules: {
          bt: [{
            required: true,
            message: '请填写标题',
            trigger: ['change', 'blur'],
          }],
          nr: {
            required: true,
            message: '请填写内容',
            trigger: ['change', 'blur'],
          },
        }
      }
    },
    onLoad() {
      this.$nextTick(()=>{
        this.$refs.form1.setRules(this.rules)
      })
    },
    methods: {
      // 提交表单
      submitForm() {
				let _this = this;
        this.$refs.form1.validate().then(ok => {
          if (ok) {
            this.loading = true;
						let {bt,nr,fsr,fsdw,fsrid,fsdwid} = this.formData;
						runSQL(`{call fninserttzfs('${bt}','${nr}','${fsr}','${fsdw}',${fsrid},${fsdwid},?,?)};`).then(async res=>{
							this.loading = false
							if(res[0].P_CODE == 0){
								let recid = res[0].P_MESSAGE;
								
								for(let i=0;i<_this.formData.files.length;i++){
									let file = _this.formData.files[i];
									await _this.uploadFileAsync(recid, file.path).then(f=>{
										_this.fileStr = _this.fileStr + f.fileid + ","
										runSQL(`insert into ssnydw.tbfile(fileid,filename,filepath,filesize,lastupdate,humanid,storefilename,serverid,folderid,disporder,version) values('${f.fileid}','${f.wjm}','${f.url}',100,now(),${_this.formData.fsrid},'${f.wjm}',1,${recid},1,1);`).then(i => {
											console.log(11111, i);
										});
									})
								}
								runSQL(`update ssnydw.tzfs set fj = '${_this.fileStr.substring(0,_this.fileStr.length-1)}' where recid = ${recid};`).then(u => {
									console.log(22222,u);
									this.$refs.uToast.show({
										type: 'success',
										message: "已发送",
										complete(){
											uni.navigateBack({
												delta: 1
											})
										}
									})
								})
								
							}else{
								this.$refs.uToast.show({
									type: 'error',
									message: "发送失败，请重试"
								})
							}
						})
          }else{
						this.$refs.uToast.show({
							type: 'error',
							message: "发送失败，请重试"
						})
					}
        }).catch(err => {
          
        })
      },
			chooseWxFile(){
				let _this = this;
				// #ifdef MP-WEIXIN
				wx.chooseMessageFile({
					count: 9,
					type: 'all',
					success: (res)=>{
						const tempFilePaths = res.tempFiles;
						tempFilePaths.forEach(file => {
							if(!(/png|jpg|jpeg/.test(file.path.toLocaleLowerCase()))){
								file.imgurl = fileIcon
							}else{
								file.imgurl = file.path
							}
						})
						_this.formData.files = _this.formData.files.concat(tempFilePaths)
					}
				})
				// #endif
			},
			uploadFileAsync(recid, url) {
				let _this = this;
				return new Promise( async (resolve, reject)=>{
					await uni.uploadFile({
						url: uploadFilePath, // 仅为示例，非真实的接口地址`${zhhfurl}zhhf-info/WeChat/getOpenId`,
						filePath: url,
						name: 'file',
						formData: {
							recid: recid
						},
						success: (res) => {
							let data = JSON.parse(res.data);
							let reg =  new RegExp("\\/"+data.wjm);
							let url_n = data.url.replace(/D:\/\/SSNYDWFile/,'').replace(reg, '');
							data.url = url_n;
							resolve(data)
						}
					});
				})
			},
			previewImg(index){
				
			},
			deleteItem(item,index){
				this.formData.files.splice(index, 1)
			}
    }
  }
</script>

<style lang="scss" scoped>
	.su-uploader{
	  display: flex;
	  flex-wrap: wrap;
	  &-handler{
	    width: 140upx;
	    height: 140upx;
	    border-radius: 6px;
	    background-color: #f7f7f7;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    font-size: 32px;
	    color: #999;
	    margin-right: 20upx;
	    line-height: 1;
	    &:active{
	      opacity: 0.6;
	    }
	  }
	  
	  &-images{
	    width: 140upx;
	    height: 140upx;
	    border-radius: 6px;
	    position: relative;
	    &-delete{
	      position: absolute;
	      width: 54upx;
	      height: 54upx;
	      background-color: rgba(0,0,0,0.6);
	      display: flex;
	      justify-content: center;
	      align-items: center;
	      color: #fff;
	      z-index: 3;
	      top: 0;
	      right: 0;
	      border-radius: 0 6px 0 6px;
	      &:active{
	        opacity: 0.7;
	      }
	    }
	    &-item{
	      display: flex;
	      position: relative;
	      margin-right: 20upx;
	    }
	  }
	}
</style>
